package info.sgu.ttdt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import info.androidhive.slidingmenu.R;
import info.sgu.ttdt.adapter.DatabaseHelper;
import info.sgu.ttdt.adapter.JsonUrl;
import info.sgu.ttdt.model.TaiKhoan;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class TaiKhoanFragment extends ListFragment {

	private ProgressDialog pDialog;

	// URL to get contacts JSON
	private static String url;

	// JSON Node names
	private static final String tag_masinhvien = "masinhvien";
	private static final String tag_tensinhvien = "tensinhvien";
	private static final String tag_lop = "lop";
	private static final String tag_nganh = "nganh";
	private static final String tag_khoa = "khoa";
	private static final String tag_hedaotao = "hedaotao";
	private static final String tag_khoahoc = "khoahoc";

	DatabaseHelper db;
	List<TaiKhoan> datalist;
	// contacts JSONArray
	JSONArray data = null;
	ViewFlipper viewFlipper;

	// Hashmap for ListView
	ArrayList<HashMap<String, String>> dataList;

	Button btn_Add;
	Button btn_Ok;
	Button btn_Back;
	Button btn_BackNew;
	Button btn_Clear;
	Button btn_Delete;
	Button btn_SetDefault;

	EditText txt_masv;
	EditText txt_pass;

	boolean thanhcong;

	TextView txt1;
	TextView txt2;
	TextView txt3;
	TextView txt4;
	TextView txt5;
	TextView txt6;
	TextView txt7;
	TextView txt_Default;

	TaiKhoan tkk;

	public TaiKhoanFragment() {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_taikhoan, container,
				false);
		SharedPreferences settings = getActivity()
				.getSharedPreferences("UserInfo", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("type", 1);
		editor.commit();
		viewFlipper = (ViewFlipper) rootView.findViewById(R.id.viewFlipper1);
		txt1 = (TextView) rootView.findViewById(R.id.text01);
		txt2 = (TextView) rootView.findViewById(R.id.text02);
		txt3 = (TextView) rootView.findViewById(R.id.text03);
		txt4 = (TextView) rootView.findViewById(R.id.text04);
		txt5 = (TextView) rootView.findViewById(R.id.text05);
		txt6 = (TextView) rootView.findViewById(R.id.text06);
		txt7 = (TextView) rootView.findViewById(R.id.text07);
		txt_Default = (TextView) rootView.findViewById(R.id.textView_default);
		txt_Default.setText("Default: "
				+ settings.getString("masinhvien", "").toString() + " - "
				+ settings.getString("tensinhvien", "").toString());

		btn_Add = (Button) rootView.findViewById(R.id.button_add);
		btn_Add.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				viewFlipper.showNext();
				viewFlipper.showNext();
			}
		});
		txt_masv = (EditText) rootView.findViewById(R.id.editText_masv);
		txt_pass = (EditText) rootView.findViewById(R.id.editText_pass);
		btn_Ok = (Button) rootView.findViewById(R.id.button_addnew);
		btn_Ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String masv = txt_masv.getText().toString();
				if (db.checkTaiKhoan(masv))
					Toast.makeText(getActivity(), "Tài khoản đã tồn tại!",
							Toast.LENGTH_SHORT).show();
				else {
					url = JsonUrl.getUrlTaiKhoan(masv);
					thanhcong = false;
					new GetContacts().execute();
				}
			}
		});
		btn_Delete = (Button) rootView.findViewById(R.id.button_delete);
		btn_Delete.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (tkk != null) {
					String masv = tkk.getMasinhvien();
					db.deleteTaiKhoan(masv);
					db.deleteThoiKhoaBieu(masv);
					db.deleteDiem(masv);
					db.deleteDiemTQ(masv);
					db.deleteLichThi(masv);
					db.deleteTuan(masv);
					db.deleteHocKy(masv, "tkb");
					db.deleteHocKy(masv, "diem");
					db.deleteHocKy(masv, "thi");
					db.deleteBookmark(masv, "Thời khóa biểu");
					db.deleteBookmark(masv, "Điểm thi");
					db.deleteBookmark(masv, "Lịch thi");
					SharedPreferences settings = getActivity()
							.getSharedPreferences("UserInfo", 0);
					String masv2 = settings.getString("masinhvien", "")
							.toString();
					if (masv.equals(masv2)) {
						SharedPreferences.Editor editor = settings.edit();
						editor.putString("masinhvien", "null");
						editor.putString("tensinhvien", "null");
						editor.commit();
						txt_Default.setText("Default: null - null");
					}
					ReLoad();
					viewFlipper.showPrevious();
				}

			}
		});
		btn_Clear = (Button) rootView.findViewById(R.id.button_clear);
		btn_Clear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences settings = getActivity()
						.getSharedPreferences("UserInfo", 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("masinhvien", "null");
				editor.putString("tensinhvien", "null");
				editor.commit();
				txt_Default.setText("Default: null - null");
			}
		});
		btn_SetDefault = (Button) rootView.findViewById(R.id.button_setdefault);
		btn_SetDefault.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (tkk != null) {
					SharedPreferences settings = getActivity()
							.getSharedPreferences("UserInfo", 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString("masinhvien", tkk.getMasinhvien());
					editor.putString("tensinhvien", tkk.getTensinhvien());
					editor.commit();
					txt_Default.setText("Default: " + tkk.getMasinhvien()
							+ " - " + tkk.getTensinhvien());
				}

			}
		});
		btn_Back = (Button) rootView.findViewById(R.id.button_back);
		btn_Back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ReLoad();
				viewFlipper.showPrevious();
			}
		});
		btn_BackNew = (Button) rootView.findViewById(R.id.button_backnew);
		btn_BackNew.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ReLoad();
				viewFlipper.showPrevious();
				viewFlipper.showPrevious();

			}
		});

		db = new DatabaseHelper(getActivity());
		datalist = new ArrayList<TaiKhoan>();
		dataList = new ArrayList<HashMap<String, String>>();

		ReLoad();

		return rootView;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		tkk = datalist.get(position);
		viewFlipper.showNext();
		txt1.setText("Mã sinh viên: " + tkk.getMasinhvien());
		txt2.setText("Tên sinh viên: " + tkk.getTensinhvien());
		txt3.setText("Lớp: " + tkk.getLop());
		txt4.setText("Ngành: " + tkk.getNganh());
		txt5.setText("Khoa: " + tkk.getKhoa());
		txt6.setText("Hệ đào tạo: " + tkk.getHedaotao());
		txt7.setText("Khóa học: " + tkk.getKhoahoc());
	}

	private class GetContacts extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage("Vui lòng chờ...");
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();

			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);
					JSONObject c = jsonObj.getJSONObject("taikhoan");
					if (c != null) {
						String masinhvien = c.getString(tag_masinhvien);
						String tensinhvien = c.getString(tag_tensinhvien);
						String lop = c.getString(tag_lop);
						String nganh = c.getString(tag_nganh);
						String khoa = c.getString(tag_khoa);
						String hedaotao = c.getString(tag_hedaotao);
						String khoahoc = c.getString(tag_khoahoc);
						String pass = txt_pass.getText().toString();
						TaiKhoan tk = new TaiKhoan(masinhvien, tensinhvien,
								lop, nganh, khoa, hedaotao, khoahoc, pass);
						db.createTaiKhoan(tk);
						thanhcong = true;
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}
			return null;

		}

		@Override
		protected void onPostExecute(Void result) {

			super.onPostExecute(result);
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();

			if (thanhcong)
				Toast.makeText(getActivity(), "Thêm thành công!",
						Toast.LENGTH_SHORT).show();
			else
				Toast.makeText(getActivity(), "Sinh viên không tồn tại!",
						Toast.LENGTH_SHORT).show();

		}

	}
	
	protected void ReLoad()
	{
		dataList.clear();
		datalist = db.getAllTaiKhoans();
		for (TaiKhoan c : datalist) {
			HashMap<String, String> data = new HashMap<String, String>();
			data.put(tag_masinhvien,
					"Mã sinh viên: " + c.getMasinhvien());
			data.put(tag_tensinhvien,
					"Tên sinh viên: " + c.getTensinhvien());
			// adding contact to contact list
			dataList.add(data);
		}

		ListAdapter adapter = new SimpleAdapter(getActivity(),
				dataList, R.layout.list_item2, new String[] {
						tag_masinhvien, tag_tensinhvien, }, new int[] {
						R.id.text1, R.id.text2 });

		setListAdapter(adapter);
		int num = db.numberTaiKhoan();
		((MainActivity)getActivity()).NumberAccount(num, 1);
	}

}
